<template>
  <div style="display: flex">
    <transition name="el-zoom-in-center">
      <div style="display: flex;flex-direction: column;min-width: 220px;position: relative" v-show="isShow">
        <el-header
          style="display:flex;align-items: center;justify-content: space-between;padding: 10px;border-bottom: 1px solid #f2f2f2;">
          <div>
            <svg-icon class="primary" :icon-class="icon"/>
            <span class="primary">{{title}}</span>
          </div>
          <a><i class="el-icon-plus" style="color: #409EFF" @click="addClick"></i></a>
        </el-header>
        <el-tree highlight-current :data="categoryData" :props="defaultProps" node-key="id"
                 :expand-on-click-node="false"
                 ref="tree"
                 @node-click="handleNodeClick">
            <span class="slot-t-node" slot-scope="{ node, data }">
                <i
                  :class="{'el-icon-folder primary': data.id=='', 'el-icon-delete primary':data.id=='del', 'el-icon-folder-delete primary':data.id=='not'}"/>
                <span>{{ data.name }}</span>

            </span>
        </el-tree>
        <el-dialog custom-class="dialog" :title="dialogTitle" width="44%" :modal-append-to-body="false"
                   :before-close="dialogClose" v-el-drag-dialog :visible="dialogShow">
          <el-form ref="categoryForm" :model="treeFormData" label-width="80px">
            <el-form-item label="分类名称" prop="name"
                          :rules="[{required: true, message: '请输入分类名称', trigger: 'blur'},{min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}]">
              <el-input v-model="treeFormData.name"></el-input>
            </el-form-item>
            <el-form-item label="上级分类">
              <el-input v-model="categoryName" suffix-icon="el-icon-search" @focus="chooseTreeDialog"/>
            </el-form-item>
            <el-form-item label="分类图标">
              <single-upload v-model="treeFormData.thumbnail"></single-upload>
            </el-form-item>
          </el-form>
          <div class="dialog-button-slot">
            <el-button @click="dialogClose">取 消</el-button>
            <el-button type="primary" @click="dialogConfirm('categoryForm')">确 定</el-button>
          </div>
          <category-dialog ref="categoryDialog" :request="request" @confirm="categoryDialogConfirm"/>
        </el-dialog>
      </div>
    </transition>

    <div class="leftBotton_Css" @click="leftBotton">
      <a style="width: 100%">
        <div class="left_css">
          <i :class="[isShow ?'el-icon-caret-left':'el-icon-caret-right']"></i>
        </div>
      </a>
    </div>
  </div>
</template>

<script>
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import utils from '../../utils/utils.js'
  import SingleUpload from '@/components/Upload/singleUpload'
  import CategoryDialog from '@/components/CategoryDialog'
  import request from '@/utils/request'

  export default {
    directives: {elDragDialog},
    data() {
      return {
        isShow: true,
        categoryData: [{
          name: '所有分类',
          id: '',
          childrens: []
        }],
        defaultProps: {
          children: 'childrens',
          label: 'name'
        },
        dialogTitle: '',
        dialogShow: false,
        categoryName: '',
        treeFormData: {
          id: '',
          name: '',
          thumbnail: '',
          parentId: ''
        },
        flag: 'save',
        category: {},
      }
    },
    props: {
      icon: '',
      title: '',
      request: '',
      
    },
    components: {
      SingleUpload,
      CategoryDialog
    },
    created() {
      this.loadList()
    },
    methods: {
      loadList() {
        let _this = this;
        request({
          url: '/admin/' + this.request + '/list',
          method: 'get',
        }).then(response => {
          console.log(response)
          _this.categoryData[0].childrens = response.data
        }).catch(error => {
        })
      },
      leftBotton: function () {
        this.isShow = !this.isShow
      },

      handleNodeClick(object, Node, element) {
        if (object.id == 'not') {
          //未分类
          this.$emit('notClick')
        } else if (object.id == 'del') {
          //回收站
          this.$emit('delClick')
        } else {
          this.$emit('nodeClick', object)
        }
        this.category = object;
      },
      addClick() {
        this.dialogTitle = '新增分类';
        this.flag = 'save';
        this.categoryName = this.category.name;
        this.treeFormData.parentId = this.category.id;
        this.treeFormData.id = '';
        this.treeFormData.name = '';
        this.treeFormData.thumbnail = '';
        this.dialogShow = true
      },
      editClick() {
        let _this = this;
        this.dialogTitle = '修改分类';
        this.flag = 'update'
        this.treeFormData.id = this.category.id;
        this.treeFormData.parentId = this.category.parentId;
        console.log(this.category.parentId)
        if (!utils.isNull(this.category.parentId)) {
          let obj = utils.findTree(this.category.parentId, _this.categoryData[0].childrens)
          this.categoryName = obj.name;
        } else {
          this.categoryName = '所有分类';
        }
        this.treeFormData.name = this.category.name;
        this.treeFormData.thumbnail = this.category.thumbnail;
        this.dialogShow = true
      },
      delClick() {
        const _this = this
        this.$confirm('确认删除' + this.category.name + '?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          request({
            url: '/admin/' + this.request + '/del/' + this.category.id,
            method: 'post',
          }).then(response => {
            console.log(response)
            _this.$message({
              type: 'success',
              message: '删除成功!',
              offset: 120,
              center: true
            })
            // 更新列表数组
            if (!utils.isNull(_this.category.parentId)) {
              const obj = utils.findTree(_this.category.parentId, _this.categoryData[0].childrens)
              obj.childrens.forEach(function (item, index) {
                if (item.id == _this.category.id) {
                  // 因为obj是_this.tableData取出来的，所以是同一指针，改变obj也会改变_this.tableData
                  obj.childrens.splice(index, 1)
                }
              })
            } else {
              // 没父节点就肯定是根结点
              _this.categoryData[0].childrens.forEach(function (item, index) {
                if (item.id == _this.category.id) {
                  _this.categoryData[0].childrens.splice(index, 1)
                }
              })
            }
            _this.category = {};
          }).catch(error => {

          })
        }).catch(() => {
        })
      },
      dialogClose() {
        this.dialogShow = false
      },
      dialogConfirm(form) {
        const _this = this
        this.$refs[form].validate((valid) => {
          if (valid) { // 校验表单
            request({
              url: '/admin/' + _this.request + '/' + _this.flag,
              method: 'post',
              data: _this.treeFormData
            }).then(response => {
              console.log(response)
              if (_this.flag == 'save') {
                if (!utils.isNull(response.data.parentId)) {
                  let obj = utils.findTree(response.data.parentId, _this.categoryData[0].childrens)
                  obj.childrens.splice(0, 0, response.data)
                } else {
                  // 没父节点就肯定是根结点
                  _this.categoryData[0].childrens.splice(0, 0, response.data)
                }
              } else {
                let currentObj = utils.findTree(_this.category.id, _this.categoryData[0].childrens)//找到当前子节点
                let currentParentObj = utils.findTree(_this.category.parentId, _this.categoryData[0].childrens)//找到之前的父节点
                let nowParentObj = utils.findTree(response.data.parentId, _this.categoryData[0].childrens)//找到现在的父节点

                if (!utils.isNull(response.data.parentId)) {

                  if (_this.category.parentId != response.data.parentId) { //代表换了父节点
                    console.log('3333')
                    //删掉之前父节点下的子节点
                    console.log(currentParentObj)
                    console.log(_this.category.id)
                    if (!utils.isNull(currentParentObj)) {
                      currentParentObj.childrens.forEach(function (item, index) {
                        if (item.id == _this.category.id) {
                          currentParentObj.childrens.splice(index, 1)
                        }
                      })
                    }else {
                      _this.categoryData[0].childrens.forEach(function (item, index) {
                        if (item.id == _this.category.id) {
                          _this.categoryData[0].childrens.splice(index, 1)
                        }
                      })
                    }
                    for (let key in response.data) {
                      if (key != 'childrens') {
                        currentObj[key] = response.data[key]
                      }
                      console.log('4444')
                    }
                    //再往现在的父节点push修改好值的子节点
                    nowParentObj.childrens.splice(0, 0, currentObj)
                  } else {//没换父节点
                    //循环更新数据
                    for (let key in response.data) {
                      if (key != 'childrens') {
                        currentObj[key] = response.data[key]
                      }
                    }
                  }
                } else {
                  // 没父节点就肯定是根结点
                  //循环更新数据
                  for (let key in response.data) {
                    if (key != 'childrens') {
                      currentObj[key] = response.data[key]
                    }
                  }
                }
              }
              _this.dialogShow = false;
            }).catch(error => {
            })

          } else {
            console.log('error submit!!')
            return false
          }
        })

      },
      categoryDialogConfirm(val) {
        console.log(val)
        this.treeFormData.parentId = val.id
        this.categoryName = val.name
      },
      chooseTreeDialog() {
        if (this.flag == 'save') {
          this.$refs.categoryDialog.show()
        } else {
          this.$refs.categoryDialog.show(this.category.id)
        }
      },
      upwardClick(data) {
        var _this = this;
        _this.sorting = [];
        event.stopPropagation();
        console.log(data)
        if (!utils.isNull(data.parentId)) {
          const obj = utils.findTree(data.parentId, _this.categoryData[0].childrens)
          obj.childrens.forEach(function (item, index) {
            if (item.id == data.id) {
              if (index > 0) {
                var form = item;
                _this.$refs.tree.remove(item);
                _this.$refs.tree.insertBefore(form, obj.childrens[index - 1]);
                console.log(_this.categoryData[0].childrens)
              }
            }
          });
          obj.childrens.forEach(function (item, index) {
            var sorting = {
              id: item.id,
              orders: index + 1,
              name: item.name
            }
            _this.sorting.push(sorting)
          })
        } else {
          // 没父节点就肯定是根结点
          _this.categoryData[0].childrens.forEach(function (item, index) {
            if (item.id == data.id) {
              if (index > 0) {
                var form = item;
                _this.$refs.tree.remove(item);
                _this.$refs.tree.insertBefore(form, _this.categoryData[0].childrens[index - 1]);
              }
            }
          });
          _this.categoryData[0].childrens.forEach(function (item, index) {
            var sorting = {
              id: item.id,
              orders: index + 1,
              name: item.name
            }
            _this.sorting.push(sorting)
          })
        }
        _this.sorting.forEach(function (item) {
          _this.sortClick(item)
        })
      },
      downClick(data) {
        var _this = this
        event.stopPropagation();
        var orders = '';
        var form = {};
        var indexs = '';
        _this.sorting = []
        if (!utils.isNull(data.parentId)) {
          const obj = utils.findTree(data.parentId, _this.categoryData[0].childrens);
          orders = obj.childrens.length
          obj.childrens.forEach(function (item, index) {
            if (item.id == data.id) {
              form = item;
              indexs = index;
            }
          });
          //写在for循环里面会有问题
          if (indexs < orders - 1) {
            _this.$refs.tree.remove(form);
            _this.$refs.tree.insertAfter(form, obj.childrens[indexs]);
          }
          obj.childrens.forEach(function (item, index) {
            var sorting = {
              id: item.id,
              orders: index + 1,
              name: item.name
            };
            _this.sorting.push(sorting)
          })
          console.log(_this.sorting)
        } else {
          // 没父节点就肯定是根结点
          orders = _this.categoryData[0].childrens.length
          _this.categoryData[0].childrens.forEach(function (item, index) {
            if (item.id == data.id) {
              form = item;
              indexs = index;
            }
          });
          //写在for循环里面会有问题
          if (indexs < orders - 1) {
            _this.$refs.tree.remove(form);
            _this.$refs.tree.insertAfter(form, _this.categoryData[0].childrens[indexs]);
          }
          _this.categoryData[0].childrens.forEach(function (item, index) {
            var sorting = {
              id: item.id,
              orders: index + 1,
              name: item.name
            }
            _this.sorting.push(sorting)
          })
        }
        _this.sorting.forEach(function (item) {
          _this.sortClick(item)
        })
      },
      sortClick(sorting) {
        request({
          url: '/admin/' + this.request + '/update',
          method: 'post',
          data: sorting
        }).then(response => {
          console.log(response)
        }).catch(error => {
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .dialog {
    .el-dialog__header {
      border-bottom: 1px solid #eee;
    }
  }

  .dialog-button-slot {
    width: 100%;
    padding-top: 20px;
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
  }

  .leftBotton_Css {
    min-height: calc(100vh - 84px);
    background-color: #f2f2f2;
    width: 8px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }

  .left_css {
    width: 100%;
    height: 50px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    background-color: #999999;
    border-radius: 2px;
  }
</style>
